<template>
    <div class="dhz_indent">

        <div class="d_in-query bcwh p10 mb10 br5 bs1g">
            <el-form :model="queryorder" :rules='rules' ref='queryorder' label-width="60px" >
                <el-form-item label="筛选" class="mt10 mb10 d_iq-form-item">
                    <el-col :span="3">
                        <el-select v-model="queryorder.select" @change="replacement('queryorder')">
                            <el-option label="订单状态" value="0"></el-option>
                            <el-option label="支付方式" value="1"></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="orderState" v-if="queryorder.select === '0'">
                            <el-select v-model="queryorder.orderState" placeholder="请选择搜索的订单状态">
                                <el-option label="待支付" value="0"></el-option>
                                <el-option label="已支付" value="1"></el-option>
                                <el-option label="超时未支付" value="2"></el-option>
                                <el-option label="被取消" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item prop="payMethod" v-else>
                            <el-select v-model="queryorder.payMethod" placeholder="请选择搜索的订单支付方式">
                                <el-option label="微信支付" value="0"></el-option>
                                <el-option label="支付宝" value="1"></el-option>
                                <el-option label="到店支付" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="pl10">
                        <el-button type="primary" @click="currentPage=1,pageingstate=2;requestquery('queryorder')">搜索</el-button>
                        <el-button type="danger" @click="currentPage=1,pageingstate=0;replacement('queryorder'),requestdhorder()">取消</el-button>
                    </el-col>
                </el-form-item>
            </el-form>
        </div>

        <div class="d_in-list tc bcwh p10 br5 bs1g">
            <table class="d_inl-table f14">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户(ID)</th>
                        <th>价格<br><span class="n f12 b00a tl">*点店铺名(蓝字)看明细</span></th>
                        <th>订单状态</th>
                        <th>创建时间</th>
                        <th>支付方式</th>
                        <th>收货地址</th>
                        <th>优惠券</th>
                        <th>商品数量</th>
                        <!-- <th>编辑</th>   -->
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,key) in dhorder" :key="key">
                        <td>{{item.id}}</td>
                        <td>{{item.userid | filteruser}}</td>
                        <td class="tl pl20">总价：<span class="f16 ff53">{{item.totalMoney}}</span><br><br>
                            <span v-for="(items,keys) in orderitems" :key="keys" v-if="item.id === items.orderid">
                                <p><router-link :to="'/indent/ingoods/'+JSON.stringify({id:items.id,shopid:items.shopId})" class="b00a">{{items.shopId | filtershops}}：</router-link><span class="ff53">{{items.totalMoney}}</span></p>
                            </span>
                        </td>
                        <td>{{item.orderState | filterorder}}</td>
                        <td>{{item.createTime*1000 | formatDate}} {{item.createTime*1000 | formatDateBehind}}</td>
                        <td>{{item.payMethod | filterpay}}</td>
                        <td>{{item.addressid | filterlocation}}</td>
                        <td>{{item.userCouponid | filtercoupont}}
                        </td>
                        <td>{{item.number}}</td>
                        <!-- <td>
                            <button type="button" class="bc4a br5 wh pt5 pb5">编辑</button>
                        </td> -->
                    </tr>
                </tbody>
            </table>
            <div class="d_inl-paging tl">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
let axios = require('axios')
import {formatDate} from '../../js/time.js'
let that
export default {
    components: {},
    data() {
        return {
            token: '',
            dhorder:[],                         //总订单
            orderitems:[],                      //单店订单
            userman:[],                         //用户
            dcoupont:[],                        //优惠券
            location: [],                       //地址
            shops: [],                          //店铺
            // 查询绑定
            queryorder: {
                select: '0',
                orderState: '',
                payMethod: ''
            },
            // 输入验证
            rules:{
                orderState:[
                    {required:true,message:'请选择搜索的订单状态',trigger:'change'}
                ]
            },
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,                           //总数据条数
        };
    },
    filters:{
        // 订单项
        filteritem(old){
            that.items.forEach((item)=>{
                item.shopId === old ? (
                    old = item.totalMoney,
                    console.log(item.id)
                ) : '';
            })
            return old
        },
        //用户
        filteruser(user){
            that.userman.forEach((item)=>{
                item.id === user ? user = item.name : '';
            })
            return user
        },

        // 优惠券
        filtercoupont(cou){
            that.dcoupont.forEach((item)=>{
                if(item.id === cou){
                    switch(item.type){
                        case 0: cou = "满减券",console.log(item.type);
                        break;
                        case 1: cou = '折扣券';
                        break;
                        default: cou = '返现券';
                        break;
                    }
                }else{return}
            })
            return cou
        },

        // 收货地址
        filterlocation(tion){
            that.location.forEach((item)=>{
                item.id === tion ? tion = item.address : '';
            })
            return tion
        },

        // 店铺
        filtershops(shop){
            that.shops.forEach((item)=>{
                item.id === shop ? shop = item.name : '';
            })
            return shop
        },
        // 支付方式
        filterpay(num){
            if(num === 0){
                num = '微信支付'
            }else if(num === 1){
                num = '支付宝'
            }else{num = '到店付款'}
            return num
        },
        // 订单状态
        filterorder(state){
            if(state === 0){
                state = '待支付'
            }else if(state === 1){
                state = '已支付'
            }else if(state === 2){
                state = '超时未支付'
            }else{state = '用户取消'}
            return state
        },

        // 时间戳过滤器
        formatDate(time){
            var date = new Date(time);
            return formatDate(date,'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date,'hh:mm:ss')
        },
    },
    computed: {},
    watch: {},
    methods: {
        //取消验证
        replacement(verify){
            this.$refs[verify].resetFields();
        },

        // 查询验证
        requestquery(verify){
            this.$refs[verify].validate((valid)=>{
                if(valid){
                    that.requestdhorder()
                }else{return}
            })
        },
        // 订单接口
        requestdhorder(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize}
            for(var i in that.queryorder) i!=='select' && that.queryorder[i]!=='' ?  data[i] = that.queryorder[i] : '';
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: '/api/dhorder/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.dhorder = resp.data.data;
                that.total = resp.data.code;
                if(that.pageingstate === 2){
                    resp.data.code === 0 ? this.$message('没有符合条件的订单') : 
                    this.$message({
                        message: '为您找到'+resp.data.code+'条订单消息',
                        type: 'success'
                    });
                }else{}
            }).catch( err=> {console.log(err)})
        },

        // 用户名
        requestuser(){
            let data = {current:1,size:10000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/user/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.userman = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        name: item['nickname']
                    }
                })
                // console.log(that.userman)
            }).catch( err=> {console.log(err)})
        },

        // 优惠券
        requestdcoupont(){
            let data = {current:1,size:10000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/userCoupon/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.dcoupont = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        type: item['type'],
                        full: item['full'],
                        reduce: item['reduce'],
                        discount: item['discount'],
                        rebate: item['rebate']
                    }
                })
                // console.log(that.dcoupont)
            }).catch( err=> {console.log(err)})
        },

        // 地址
        requestlocation(){
            let data = {current:1,size:10000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/userAddress/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.location = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        address: item['address']
                    }
                })
                // console.log(that.location)
            }).catch( err=> {console.log(err)})
        },

        // 店铺
        requestshops(){
            let data = {current:1,size:10000000};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/shop/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.shops = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        name: item['name']
                    }
                })
                // console.log(that.shops)
            }).catch( err=> {console.log(err)})
        },

        // 订单项接口
        requestitems(){
            let that = this;
            let data = {current:1,size:100000000}
            let updata = JSON.stringify(data)
            axios({
                method: 'post',
                url: '/api/dhorderItems/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                that.orderitems = resp.data.data;
            }).catch( err=> {console.log(err)})
        },


        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            that.requestdhorder()
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            that.currentPage = val;
            that.requestdhorder()
        },

        //拿token
        newtoken(){
			console.log('运行了')
			let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requestuser()
                that.requestdcoupont()
                that.requestlocation()
                that.requestshops()
                that.requestitems()
                setTimeout(()=>{
                    that.requestdhorder()
                },300)
			}).catch( err=> {})
		},
    },
    created() {},
    mounted() {
        let that = this;
        //that.token = JSON.parse(sessionStorage.getItem('token'))
        that.newtoken()
        
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhz_indent{
    height: calc(100% - 56px);
    box-sizing: border-box;
}
/* 查询 */
.d_iq-form-item .el-select{
    width: 100%;
}
/* 列表 */
.d_in-list{
    height: calc(100% - 90px);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    box-sizing: border-box;
}
.d_inl-table{
    width: 100%;
    color: #666666;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid  #e0e0e0;
    border-collapse: collapse; 
}
.d_inl-table thead tr,.d_inl-table tbody tr:hover{
    background-color: #F2F2F2;
}
.d_inl-table th, .d_inl-table td{
    min-height: 50px;
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_inl-table tr td img{
    max-width: 120px;
    max-height: 80px;
}
</style>